package basic.socket.chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.List;

/**
 * @author bingo
 * @Description
 * @Date 2018/7/22
 */
public class ServerThread implements Runnable {

    private  DataOutputStream dos;
    private  DataInputStream dis;
    private  boolean isRunning;
    private List<ServerThread> threads;
    private String msg;
    private String name;
    public ServerThread(Socket socket,List<ServerThread> threads) {
        isRunning = true;
        this.threads = threads;
        try {
            dis = new DataInputStream(socket.getInputStream());
            name = dis.readUTF();
            dos = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        first();
    }

    public void receive(){
        try {
            msg  = dis.readUTF();
            System.out.println("服务端收到来自"+name+"的消息---》"+msg);
        } catch (IOException e) {
            isRunning = false;
        }
        send(name+"："+msg);
        board(msg);
    }

    public void first(){
        send("欢迎你进入聊天室!");
        notify(name+"进入了聊天室");
    }
/**
 *
 * 向其他人发送
 *
 * */


    public void board(String message){
        for(ServerThread serverThread:threads){
         if(serverThread == this){
             continue;
          }

              serverThread.send(name + ":" + message);
         }
    }
    public void notify(String message){
        for(ServerThread serverThread:threads){
            if(serverThread == this){
                continue;
            }
            serverThread.send(message);
        }
    }

    /**
     *
     *  向自己发送。。
     *
     * */
    public void  send(String message){
        try {
            dos.writeUTF(message);
            dos.flush();
        } catch (IOException e) {
            isRunning = false;
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
      while (isRunning) {
          receive();
      }
    }
}
